package com.example.student.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.student.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(token)) {
            try{
                Claims claims = jwtUtils.parseJwt(token);
                request.setAttribute("user_claims",claims);
                return true;
            }catch (Exception e){
                throw new BizException(CommonEnum.UN_AUTHORISE);
            }

        }
        throw new BizException(CommonEnum.UN_AUTHORISE);
    }
}
